<template>
  <div class="carbon-credit-page">
    <!-- 顶部资产概览栏 -->
    <div class="top-header">
      <div class="header-left">
        <i class="el-icon-money"></i>
        <span class="title">我的碳信用资产</span>
      </div>
      <div class="header-middle">
        <span class="stat-item">持仓总量 <span class="stat-value">{{holdTotal}} (tCO₂e)&nbsp;|</span></span>  
        <span class="stat-item">可用数量 <span class="stat-value">{{available}} (tCO₂e)&nbsp;|</span></span> 
        <span class="stat-item">锁定数量 <span class="stat-value">{{locked}}(tCO₂e) &nbsp;|</span></span> 
        <span class="stat-item">冻结数量 <span class="stat-value">{{frozen}}(tCO₂e)</span></span>
      </div>
      <div class="header-right">
        <el-button type="primary" plain @click="fromVisible = true; dialogTitle = '上传碳信用项目'"
          >上传</el-button
        >
        <el-button type="success"  plain  @click="dialogVisible = true">我想买</el-button>
      </div>
    </div>

    <!-- 筛选条件区域 -->
    <div class="filter-section">
      <el-row :gutter="20" class="filter-row">
        <el-col :span="4">
          <div class="filter-item" style="display: flex; align-items: center">
            <span class="filter-label">核证标准</span>
            <el-select
              v-model="form.certificationCriteria"
              placeholder="全部"
              clearable
              class="filter-select"
              style="flex: 1"
              @change="resetMainPagination"
            >
              <el-option v-for="item in certificationCriteria" :label="item.itemCh" :value="item.itemValue":key="item.id" ></el-option>
            </el-select>
          </div>
        </el-col>

         <el-col :span="4">
          <div class="filter-item" style="display: flex; align-items: center;"> 
            <span class="filter-label">交易状态</span> 
            <el-select
              v-model="form.transactionStatus"
              placeholder="全部"
              clearable
              class="filter-select"
              style="flex: 1"
              @change="resetMainPagination"
            >
              <el-option v-for="item in transactionStatus" :label="item.itemCh" :value="item.itemValue":key="item.id" ></el-option>
            </el-select>
          </div>
        </el-col>

         <el-col :span="4">
          <div class="filter-item" style="display: flex; align-items: center;"> 
            <span class="filter-label">资产状态</span> 
            <el-select
              v-model="form.assetsStatus"
              placeholder="全部"
              clearable
              class="filter-select"
              style="flex: 1"
              @change="resetMainPagination"
            >
              <el-option v-for="item in assetsStatus" :label="item.itemCh" :value="item.itemValue":key="item.id" ></el-option>
            </el-select>
          </div>
        </el-col>

        <el-col :span="8">
      <div class="filter-item" style="display: flex; align-items: center; gap: 10px;"> 
        <span class="filter-label">签发日期</span> 
        <el-date-picker
          v-model="form.issueDateStart"
          style="flex: 1;"
          type="date"
          placeholder="开始时间"
          clearable
          class="filter-date"
        ></el-date-picker>
        <span style="white-space: nowrap;">至</span>
        <el-date-picker
          v-model="form.issueDateEnd"
          style="flex: 1;"
          type="date"
          placeholder="结束时间"
          clearable
          class="filter-date"
        ></el-date-picker>
      </div>
</el-col>

      </el-row>

      <!-- 第二行搜索 -->
      <el-row :gutter="20" class="search-row" style="margin-top: 10px">
        <el-col :span="8">
          <div style="display: flex;" class="filter-item">
            <span style="margin-top: 8px;" class="filter-label2">按项目搜索</span>
            <div class="search-container">
              <el-input
                v-model="form.projectName"
                placeholder="输入项目名称"
                clearable
                class="search-input"
                style="flex: 1"
                @keyup.enter.native="handleProjectSearch"
              ></el-input>
              <el-button type="success" plain @click="handleProjectSearch"
                >查询</el-button
              >
            </div>
          </div>
        </el-col>
        <el-col :span="8">
          <div style="display: flex;" class="filter-item2">
            <span style="display: 1;margin-top: 8px; " class="filter-label2">方法学搜索</span>
            <div class="search-container">
              <el-input
                v-model="form.methodology"
                placeholder="输入方法学名称"
                clearable
                class="search-input"
                @keyup.enter.native="handleMethodSearch"
              ></el-input>
              <el-button type="success" plain @click="handleMethodSearch"
                >查询</el-button
              >
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 表格数据区域 -->
    <div class="table">
      <el-table
        :data="tableData"
        stripe
        @selection-change="handleSelectionChange"
        style="width: 100%"
        v-loading="tableLoading"
      >
        <el-table-column prop="id" label="序号" align="center" width="80"></el-table-column>
        <el-table-column
          prop="projectName"
          label="项目名称"
          show-overflow-tooltip
          width="280"
        ></el-table-column>
        <el-table-column
          prop="certificationCriteria"
          label="核证标准"
          align="center"
          show-overflow-tooltip
          width="100"
        ></el-table-column>
        <el-table-column
          prop="availableAmount"
          label="持仓量(CO2e)"
          width="110"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="valuation"
          label="资产估值(¥)"
          width="130"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="projectScopeType"
          label="类型"
          align="center"
          width="130"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="assetsStatusName"
          label="资产状态"
          width="130"
          align="center"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="issuingDate"
          label="签发日期"
          width="130"
          align="center"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column label="操作" width="385" align="center">
          <template v-slot="scope">
            <div class="operation-btns">
              <span 
                class="btn-text view" 
                @click="handleView(scope.row.id)"
              >查看</span>
               <span class="btn-text offline" @click="handleOffline(scope.row)"
                >场外上架</span>
              <span 
                class="btn-text inner" 
                @click="handleInner(scope.row)"
              >场内交易</span>
              <span 
                class="btn-text modify" 
                @click="handleModify(scope.row)"
              >修改</span>
              <span 
                class="btn-text delete" 
                @click="handleDelete(scope.row.id)"
              >删除</span>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination" v-if="mainTotal > 0">
        <el-pagination
          background
          @current-change="handleMainPageChange"
          @size-change="handleMainPageSizeChange"
          :current-page="mainPageNum"
          :page-size="mainPageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :page-count="mainTotalPages"
          :page-sizes="[5, 10, 15, 20]"
        ></el-pagination>
      </div>
    </div>

    <!-- 上传弹窗 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="fromVisible"
      width="70%"
      :close-on-click-modal="false"
      destroy-on-close
      @close="resetUploadForm"
    >
      <div class="upload-dialog-content">
        <el-form
          ref="uploadForm"
          :model="uploadForm"
          size="medium"
          :rules="uploadFormRules"
        >
          <!-- 项目名称 + 选择项目按钮 -->
          <el-form-item label="项目名称" required prop="projectName">
            <el-input
              v-model="uploadForm.projectName"
              placeholder="请输入项目名称"
              style="width: 60%; margin-right: 10px"
              disabled
            ></el-input>
            <el-button
              size="small"
              type="primary"
              plain
              @click="openProjectSelector"
              >选择项目</el-button
            >
          </el-form-item>

          <!-- 采用方法学 和 类型 -->
          <el-row :gutter="20" class="form-row">
            <el-col :span="12">
              <el-form-item label="采用方法学" prop="carbonMethodologyName">
                <el-input
                  v-model="uploadForm.carbonMethodologyName"
                  placeholder="填写采用方法学"
                  style="width: 100%"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="类型" prop="type">
                <el-input
                  v-model="uploadForm.projectScopeType"
                  placeholder="填写类型"
                  style="width: 100%"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 持仓总量 和 交易单价 -->
          <el-row :gutter="20" class="form-row">
            <el-col :span="12">
              <el-form-item label="持仓总量(tCO2e)" required prop="total">
                <el-input
                  v-model.number="uploadForm.total"
                  placeholder="填写持仓总量"
                  style="width: 100%"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="交易单价(¥)" prop="buyUnitPrice">
                <el-input
                  v-model.number="uploadForm.buyUnitPrice"
                  placeholder="填写交易单价"
                  style="width: 100%"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 交易总价 和 核证机构 -->
          <el-row :gutter="20" class="form-row">
            <el-col :span="12">
              <el-form-item label="交易总价(¥)" prop="buyTotalPrice">
                <el-input
                  v-model.number="uploadForm.buyTotalPrice"
                  placeholder="自动计算或填写"
                  style="width: 100%"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="核证机构" prop="certifiedAgency">
                <el-input
                  v-model="uploadForm.certifiedAgency"
                  placeholder="填写核证机构"
                  style="width: 100%"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 签发日期 和 交易日期 -->
          <el-row :gutter="20" class="form-row">
            <el-col :span="12">
              <el-form-item label="签发日期" prop="issueDate">
                <el-date-picker
                  v-model="uploadForm.issuingDate"
                  type="date"
                  placeholder="选择签发日期"
                  style="width: 100%"
                  disabled
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="交易日期" prop="buyDate">
                <el-date-picker
                  v-model="uploadForm.buyDate"
                  type="date"
                  placeholder="选择交易日期"
                  style="width: 100%"
                ></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 交易所 -->
          <el-form-item label="交易所" prop="carbonExchange">
            <el-select
              v-model="uploadForm.carbonExchange"
              placeholder="请选择交易所"
              style="width: 30%"
            >
             <el-option
            v-for="item in deliveryExchange"
            :key="item.itemCh"  
            :label="item.itemCh" 
            :value="item.itemValue"
    ></el-option>
            </el-select>
          </el-form-item>

          <!-- 持仓凭证 和 交易凭证 -->
          <el-row :gutter="20" class="form-row">
            <el-col :span="12">
              <el-form-item label="持仓凭证" prop="holdProof">
                <el-upload
                  class="upload-demo"
                  ref="uploadHold"
                  :on-change="handleTranChange"
                  :on-remove="removeFileList"
                  accept=".pdf,.docx,.xlsx,.xls,.jpg,.png"
                  style="width: 180px"
                  :action="upLoadParam.url"
                  :file-list="tranFileList"
                  :auto-upload="true"
                  :headers="{ token: upLoadParam.token }"
                  :on-success="upLoadParamTranFile"
                  :on-preview="tranFilehandlePreview"
                >
                  <el-button size="small" type="primary">选择文件</el-button>
                </el-upload>
                <div v-if="uploadForm.issuingCertificatesFileName" class="file-name">
                  已选择111：{{ uploadForm.issuingCertificatesFileName }}
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="交易凭证" prop="tradeProof">
                <el-upload
                  class="upload-demo"
                  :on-change="handleTradeChange"
                  :on-remove="removeTradeFileList"
                  :on-success="upLoadParamTradeFile"
                  :on-preview="tradeFilehandlePreview"
                  accept=".pdf,.docx,.xlsx,.xls,.jpg,.png"
                  style="width: 180px"
                  :action="upLoadParam.url"
                  :file-list="tradeFileList"
                  :auto-upload="true"
                  :headers="{ token: upLoadParam.token }"
                >
                  <el-button size="small" type="primary">选择文件</el-button>
                  <div slot="tip" class="el-upload__tip">
                    
                  </div>
                </el-upload>
                <div v-if="uploadForm.buyCertificateFileName" class="file-name">
                  已选择122：{{ uploadForm.buyCertificateFileName }}
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="fromVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
      </div>
    </el-dialog>

    <!-- 项目选择弹窗 -->
    <el-dialog
      title="项目列表"
      :visible.sync="projectSelectorVisible"
      width="50%"
      @close="handleProjectSelectorClose"
    >
      <!-- 搜索区域 -->
      <div class="project-search-bar">
        <el-input
          v-model="projectSearchKey"
          placeholder="输入项目名称"
          clearable
          style="width: 70%; margin-right: 10px"
          @keyup.enter.native="fetchProjectList"
        ></el-input>
        <el-button type="primary" plain @click="fetchProjectList"
          >查询</el-button
        >
      </div>

      <!-- 项目表格 -->
      <el-table
        :data="projectList"
        :height="400"
        style="width: 100%"
        @selection-change="handleProjectSelect"
        class="project-selector-table"
        v-loading="projectLoading"
      >
        <el-table-column
          label="序号"
          type="index"
          width="60"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="projectName"
          label="名称"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="projectScope"
          label="领域"
          width="150"
        ></el-table-column>
        <el-table-column
          prop="certifiedStandard"
          label="核证标准"
          width="200"
        ></el-table-column>
        <el-table-column label="操作" width="100" align="center">
          <template v-slot="scope">
            <el-button type="text" @click="selectProject(scope.row)"
              >选择</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div
        class="project-pagination"
        style="margin-top: 15px; text-align: right"
        v-if="projectTotal > 0"
      >
        <el-pagination
          background
          @current-change="handleProjectPageChange"
          @size-change="handleProjectPageSizeChange"
          :current-page="projectPageNum"
          :page-size="projectPageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="projectTotal"
          :page-sizes="[5, 10, 15]"
        ></el-pagination>
      </div>
    </el-dialog>
    <!-- 场外上架弹窗 -->
<el-dialog
  title="场外上架"
  :visible.sync="offlineDialogVisible"
  width="50%"
  :close-on-click-modal="false"
  @close="resetOfflineForm"
  destroy-on-close
>
  <el-form
    ref="offlineForm"
    :model="offlineForm"
    :rules="offlineFormRules"
    label-width="160px"
  >
    <el-form-item label="出售数量(tCO2e)" prop="tradeQuantity">
      <el-input
        v-model.number="offlineForm.tradeQuantity"
        placeholder="请输入出售数量"
      ></el-input>
    </el-form-item>
    <el-form-item label="出售单价(¥)" prop="assetUnitPrice">
      <el-input
        v-model.number="offlineForm.assetUnitPrice"
        placeholder="请输入出售单价"
      ></el-input>
    </el-form-item>
    <el-form-item label="出售截止时间" prop="expirationDate">
      <el-date-picker
        v-model="offlineForm.expirationDate"
        type="date"
        placeholder="选择截止时间"
        clearable
      ></el-date-picker>
    </el-form-item>
    <el-form-item label="期望交割时间" prop="deliveryTime">
      <el-date-picker
        v-model="offlineForm.deliveryTime"
        type="date"
        placeholder="选择交割时间"
        clearable
      ></el-date-picker>
    </el-form-item>
    <!-- 期望交割方式 -->
<el-form-item label="期望交割方式" prop="deliveryMethod">
  <el-select
    v-model="offlineForm.deliveryMethod"
    placeholder="请选择"
    v-loading="optionsLoading"
  >
    <el-option
      v-for="item in deliveryMethod"
      :key="item.itemCh"  
      :label="item.itemCh" 
      :value="item.itemValue"
    ></el-option>
  </el-select>
</el-form-item>

<!-- 期望交割场所 -->
<el-form-item label="期望交割场所" prop="deliveryExchange">
  <el-select
    v-model="offlineForm.deliveryExchange"
    placeholder="请选择"
    v-loading="optionsLoading"
  >
   <el-option
      v-for="item in deliveryExchange"
      :key="item.itemCh"  
      :label="item.itemCh" 
      :value="item.itemValue"
    ></el-option>
  </el-select>
</el-form-item>
  </el-form>
  <template #footer>
    <span class="dialog-footer">
      <el-button  @click="resetOfflineForm">取消</el-button>
      <el-button type="primary" @click="handleOfflineSubmit">确定</el-button>
    </span>
  </template>
</el-dialog>
      <!-- 我要买 -->
<el-dialog title="采购单" :visible.sync="dialogVisible" width="600px">
    <el-form :model="form2" label-width="160px"   class="top-aligned-form" >
      <el-form-item label="采购机构*">
        <el-input v-model="form2.institutionName" placeholder="请输入采购机构"></el-input>
      </el-form-item>
      <el-form-item label="采购联系人*">
        <el-input v-model="form2.contactsName" placeholder="请输入采购联系人"></el-input>
      </el-form-item>
      <el-form-item label="联系电话*">
        <el-input v-model="form2.contactsPhone" placeholder="请输入联系电话"></el-input>
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="form2.contactsEmail" placeholder="请输入邮箱"></el-input>
      </el-form-item>
      <el-form-item label="项目领域">
        <el-select v-model="form2.projectScopeCode" placeholder="请选择">
         <el-option
            v-for="item in projectScope"
            :key="item.itemCh"  
            :label="item.itemCh" 
            :value="item.itemValue"
    ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="资产类型">
        <el-select v-model="form2.assetType" placeholder="请选择">
         <el-option
            v-for="item in assetType"
            :key="item.itemCh"  
            :label="item.itemCh" 
            :value="item.itemValue"
    ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="项目类型">
        <el-select v-model="form2.projectType" placeholder="请选择">
          <el-option
            v-for="item in projectType"
            :key="item.itemCh"  
            :label="item.itemCh" 
            :value="item.itemValue"
    ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="采购数量(CO2e)*">
        <el-input v-model="form2.tradeQuantity" placeholder="请输入采购数量"></el-input>
      </el-form-item>
      <el-form-item label="询价(¥)">
        <el-input v-model="form2.assetUnitPrice" placeholder="请输入询价"></el-input>
      </el-form-item>
      <el-form-item label="截止采购日期">
        <el-date-picker
          v-model="form2.expirationDate"
          type="date"
          placeholder="请选择截止采购日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="期望交割日期">
        <el-date-picker
          v-model="form2.deliveryTime"
          type="date"
          placeholder="请选择期望交割日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="期望交割方式">
  <el-select v-model="form2.deliveryMethod" placeholder="请选择">
   <el-option
      v-for="item in deliveryMethod"
      :key="item.itemCh"  
      :label="item.itemCh" 
      :value="item.itemValue"
    ></el-option>
  </el-select>
</el-form-item>

<el-form-item label="期望交割场所">
  <el-select v-model="form2.deliveryExchange" placeholder="请选择">
   <el-option
      v-for="item in deliveryExchange"
      :key="item.itemCh"  
      :label="item.itemCh" 
      :value="item.itemValue"
    ></el-option>
  </el-select>
</el-form-item>

    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handlecaiSubmit">提交</el-button>
    </div>
  </el-dialog>
  </div>
</template>

<script>
import {
  getFeiShuUpLoadProjectParams,
  getUpLoadFileParams,
} from "@/api/tenant";

export default {
  name: "CarbonCreditAsset",
  data() {
    return {
      //选择的项目id暂存
      rid:'',
      modifyPrice:'',
      user: JSON.parse(localStorage.getItem('user') || '{}'),
      // 场外上架弹窗控制
      offlineDialogVisible: false,
      dialogTitle: "碳信用项目上传",
      // 我要买弹窗
      dialogVisible: false,
      // 场外上架表单数据
      offlineForm: {
        contactsName: '',
        contactsPhone: '',
        contactsEmail: '',
        projectId: '',
        tradeQuantity: '', // 出售数量
        assetUnitPrice: '', // 出售单价
        expirationDate: null, // 出售截止时间
        deliveryTime: null, // 期望交割时间
        deliveryMethod: '',
        deliveryExchange: '',
        projectScope: '',
        projectScopeCode: '',
        projectType: '',
        institutionName: '',
        projectName: '',
      },
      // 场外上架表单校验规则
      offlineFormRules: {
        tradeQuantity: [
          { required: true, message: '请输入出售数量', trigger: 'blur' },
          { pattern: /^[0-9]+(\.[0-9]{1,2})?$/, message: '请输入合法数值（最多两位小数）', trigger: 'blur' }
        ],
        assetUnitPrice: [
          { required: false, message: '请输入出售单价', trigger: 'blur' },
          { pattern: /^[0-9]+(\.[0-9]{1,2})?$/, message: '请输入合法数值（最多两位小数）', trigger: 'blur' }
        ],
        expirationDate: [
          { required: false, message: '请选择出售截止时间', trigger: 'change' }
        ],
        deliveryTime: [
          { required: false, message: '请选择期望交割时间', trigger: 'change' }
        ]
      },

      optionsLoading: false,
      deliveryModeLoading: false,
      // 场外上架结束
      tranFileList: [], // 持仓凭证文件列表（原有）
      tradeFileList: [], // 交易凭证文件列表（新增）
      tranFileUrl: "", // 持仓凭证飞书地址（原有）
      tradeFileUrl: "",

      // 弹窗控制
      fromVisible: false,
      projectSelectorVisible: false,
      upLoadParams: {}, // 图片上传
      upLoadParam: {}, // 文件上传
      // 项目选择相关
      projectSearchKey: "",
      projectList: [],
      projectTotal: 0,
      projectPageNum: 1, // 项目选择弹窗当前页码（独立变量）
      projectPageSize: 5, // 项目选择弹窗每页条数（独立变量）
      projectLoading: false,

      // 主表格相关
      tableData: [],
      tableLoading: false,
      selectedProjects: [],
      projectFilter: "",
      // 主表格分页相关
      mainPageNum: 1,       // 主表格当前页码
      mainPageSize: 10,     // 主表格每页条数
      mainTotal: 0,         // 主表格总记录数

      // 我要买的form上传到后端用
      form2: {
        publisherId: '',
        // 机构名称（对应institution_name）
        institutionName: '',
        // 联系人姓名（对应contacts_name）
        contactsName: '',
        // 联系人手机（对应contacts_phone）
        contactsPhone: '',
        // 联系人邮箱（对应contacts_email）
        contactsEmail: '',
        // 项目领域（对应project_scope_code）
        projectScopeCode: '',
        // 资产类型（对应asset_type）
        assetType: '',
        // 项目类型（对应project_type）
        projectType: '',
        // 交易量（对应trade_quantity）
        tradeQuantity: '',
        // 资产单价（对应asset_unit_price）
        assetUnitPrice: '',
        // 交易截止日期（对应expiration_date）
        expirationDate: '',
        // 期望交割时间（对应delivery_time）
        deliveryTime: '',
        // 期望交割方式（对应delivery_method）
        deliveryMethod: '',
        // 交割场所
        deliveryExchange: '',
      },

      // 上传表单数据
      uploadForm: {
        id: "",
        projectName: "",
        carbonProjectId:'',
        methodologyCode:'',
        carbonExchange:'',
        carbonMethodologyName: "",
        projectScopeType: "",
        total: "",
        buyUnitPrice: "",
        buyTotalPrice: "",
        certifiedAgency: "",
        issuingDate: null,
        issuingAgency:'',
        buyDate: null,
        exchange: "",
        issuingCertificates: null,
        issuingCertificatesFileName: "",
        buyCertificate: null,
        buyCertificateFileName: "",

      },

      // 表单验证规则
      uploadFormRules: {
        projectName: [
          { required: true, message: "请选择项目名称", trigger: "blur" },
        ],
        holdTotal: [
          { required: true, message: "请填写持仓总量", trigger: "blur" },
           { 
              validator: (rule, value, callback) => {
                // 先判断是否为数字且大于 0
                if (Number(value) <= 0) {
                  callback(new Error("持仓总量必须大于 0"));
                } else {
                  callback(); // 验证通过
                }
              },
              trigger: "blur" // 失焦时触发验证
            }
        ],
        carbonMethodologyName: [
          { required: true, message: "请填写采用方法学", trigger: "blur" },
        ],
        // holdProof: [
        //   { required: true, message: "请上传持仓凭证", trigger: "change" },
        // ],
      },

      // 顶部统计数据
      holdTotal: '',
      available: '',
      locked: '',
      frozen: '',
      // 我要买的领域
      projectScope: [],
      // 我要买的资产类型
      assetType: [],
      // 我要买的项目类型
      projectType: [],
      // 交割方式列表
      deliveryMethod: [],
      // 交割场所列表
      deliveryExchange: [],

      // 核证机构
      certificationCriteria: [],
      // 交易状态
      transactionStatus: [],
      // 资产状态
      assetsStatus: [],
      // 开始时间
      issueDateStart: '',
      // 结束时间
      issueDateEnd: '',
      // 项目搜索名
      projectSearch: '',
      // 方法学搜索
      methodSearch: '',
      // 查询框返回值
      form: {
        certificationCriteria: '', // 核证标准
        transactionStatus: '',    // 交易状态
        assetsStatus: '',         // 资产状态
        projectName: '',          // 项目名称（搜索用）
        methodology: '',          // 方法学（搜索用）
        issueDateStart: '',       // 签发开始日期
        issueDateEnd: ''          // 签发结束日期
      },
    };
  },

  computed: {  
    mainTotalPages() {
    if (this.mainTotal <= 0) return 0;
    return Math.ceil(this.mainTotal / this.mainPageSize);
  },
  },

 watch: {
  fromVisible(newVal) {
    if (!newVal) {
      this.resetUploadForm();
    }
  },
  // 监听单价变化：计算总价 = 数量 × 单价
  "uploadForm.buyUnitPrice"(val) {
    // 先判断单价和数量是否为有效数字（避免NaN）
    const unitPrice = Number(val);
    const totalQuantity = Number(this.uploadForm.total);
    if (!isNaN(unitPrice) && !isNaN(totalQuantity) && unitPrice > 0 && totalQuantity > 0) {
      this.uploadForm.buyTotalPrice = (unitPrice * totalQuantity).toFixed(2); // 正确公式
    } else {
      this.uploadForm.buyTotalPrice = ""; // 无效值时清空总价
    }
  },
  // 监听数量变化：计算总价 = 数量 × 单价
  "uploadForm.total"(val) {
    const totalQuantity = Number(val);
    const unitPrice = Number(this.uploadForm.buyUnitPrice);
    if (!isNaN(totalQuantity) && !isNaN(unitPrice) && totalQuantity > 0 && unitPrice > 0) {
      this.uploadForm.buyTotalPrice = (totalQuantity * unitPrice).toFixed(2); // 正确公式
    } else {
      this.uploadForm.buyTotalPrice = ""; // 无效值时清空总价
    }
  },
},
  mounted() {
    this.form2.publisherId = this.user.tenantId || '';
    this.queryCreditSum();
    this.queryCredits();
    this.loadSelectorData();
    this.upLoadParams = getUpLoadFileParams();
    this.upLoadParam = getFeiShuUpLoadProjectParams();
  },

  methods: {
    resetOfflineForm() {
      // 关闭弹窗
      this.offlineDialogVisible = false;
      // 重置表单数据（清空所有字段）
      this.offlineForm = {
        carbonProjectId: '',
        tradeQuantity: '',
        assetUnitPrice: '',
        expirationDate: null,
        deliveryTime: null,
        deliveryMethod: '',  // 空默认值
        deliveryExchange: '',  // 空默认值
        projectScopeCode: '',
        projectScope: '',
        projectType: '',
        institutionName: ''
      };
    },
    // 提交场外上架表单
    handleOfflineSubmit() {
      this.$refs.offlineForm.validate((valid) => {
        if (valid) {
          const requestData = { ...this.offlineForm };
          this.$request.post('/trade/carbonTradeQuote/addCredit', requestData,{params:{creditId : this.rid}}).then(res => {
            if (res.code === 200) {
              this.$message.success('场外上架提交成功');
              this.offlineDialogVisible = false;
              this.queryCredits();
              this.queryCreditSum();
              this.$confirm('是否跳转到供需行情？', '确认', { type: "warning" }).then(response => {
                this.$router.push('/trade/Quote/buyQuote')
              })
            } else {
              this.$message.error(res.msg || '提交失败');
            }
          }).catch(error => {
            console.error('提交失败:', error);
          });
        }
      });
    },
    // 提交我要买
    handlecaiSubmit() {
      console.log('这是form2', this.form2)

      if (this.form2.assetType === '0140000000') {
        this.form2.assetType = ''
      }
      if (this.form2.projectType === '0040000000') {
        this.form2.projectType = ''
      }
      if (this.form2.projectScopeCode === '0030000000') {
        this.form2.projectScopeCode = ''
      }
      this.$request.post('/trade/carbonTradeQuote/addBuy', this.form2).then(res => {
        if (res.code === 200) {
          this.$message.success('采购清单提交成功');
          this.dialogVisible = false;
        } else {
          this.$message.error(res.msg || '提交失败');
        }
      })
    },
    resetUploadForm() {
      // 1. 关闭上传弹窗（而非场外弹窗）
      this.fromVisible = false;

      // 2. 重置上传表单数据（清空所有字段）
      this.uploadForm = {
        id: "",
        projectName: "",
        carbonMethodologyName: "",
        projectScopeType: "",
        total: "",
        buyUnitPrice: "",
        buyTotalPrice: "",
        certifiedAgency: "",
        issuingDate: null,
        buyDate: null,
        exchange: "",
        issuingCertificates: null,
        issuingCertificatesFileName: "",
        buyCertificate: null,
        buyCertificateFileName: "",
      };

      // 3. 清空文件上传列表（如果有）
      this.tranFileList = [];  // 持仓凭证文件列表
      this.tradeFileList = []; // 交易凭证文件列表
      this.tranFileUrl = "";   // 持仓凭证上传地址
      this.tradeFileUrl = "";  // 交易凭证上传地址

      // 4. 清除表单校验状态（如果使用了el-form的校验）
      if (this.$refs.uploadForm) {
        this.$refs.uploadForm.resetFields();
      }
    },

    // 修改回显
    handleModify(row) {
      this.dialogTitle = "修改碳信用项目";
      console.log("看看row",row)
      this.uploadForm = JSON.parse(JSON.stringify(row))
      this.modifyPrice = this.uploadForm.total
      this.fromVisible = true
    },


    async fetchDeliveryOptions(type) {
      this.optionsLoading = true;
      try {
        // 调用后端接口，传递type参数（路径参数）
        const res = await this.$request.get(`/trade/carbonTradeQuote/getDeliveryMethod/${type}`);
        // 假设后端返回格式：{ success: true, data: [] }（根据你的ApiResult结构调整）
        if (res.code == 200) {
          return res.data; // 返回查询到的列表

        } else {
          this.$message.warning("获取数据失败");
          return [];
        }
      } catch (error) {
        console.error(`获取${type}失败：`, error);
        return [];
      } finally {
        this.optionsLoading = false;
      }
    },


    loadSelectorData() {
      this.$request.get('/assets/carbonCreditAssets/querySelector').then(res => {
        if (res.code === 200) {
          this.certificationCriteria = res.data.certificationList
          this.transactionStatus = res.data.transactionStatusList
          this.assetsStatus = res.data.assetsStatusList
          this.projectScope = res.data.projectScopeList
          this.assetType = res.data.assetTypeList
          this.projectType = res.data.projectTypeList
          this.deliveryMethod = res.data.deliveryMethodList
          this.deliveryExchange = res.data.deliveryExchangeList
        }
      })
    },
    handleDelete(id) {   // 单个删除
      this.$confirm('您确定删除吗？', '确认删除', { type: "warning" }).then(response => {
        this.$request.delete('/assets/carbonCreditAssets/delCreditAssets', { params: {
          id: id
        }}).then(res => {
          if (res.code === 200) {   // 表示操作成功
            this.$message.success('操作成功')
            this.queryCreditSum();
            this.queryCredits();
          } else {
            this.$message.error(res.msg)  // 弹出错误的信息
          }
        })
      }).catch(() => {
      })
    },

    queryCredits() {
      this.tableLoading = true;
      const params = {
        ...this.form,
        tenantId: this.user.tenantId,
        pageNum: this.mainPageNum,      // 添加当前页码
        pageSize: this.mainPageSize  // 添加每页条数
      };

      // 处理默认值为空的情况
      if (params.certificationCriteria === '0070000000') {
        params.certificationCriteria = null;
      }
      if (params.transactionStatus === '0160000000') {
        params.transactionStatus = null;
      }
      if (params.assetsStatus === '0130000000') {
        params.assetsStatus = null;
      }

      this.$request.get('/assets/carbonCreditAssets/queryBySelector', {
        params: params
      }).then(res => {
        this.tableLoading = false;
        if (res.code === 200) {
          this.tableData = res.data.records || [];  // 假设数据在records字段中
          this.mainTotal = res.data.total || 0;     // 总记录数
          
        }
      }).catch(error => {
        this.tableLoading = false;
        console.error("查询资产列表失败:", error);
      });
    },

    // 打开场外上架弹窗（可绑定到表格操作按钮）
    openOfflineDialog(row) {
      // 若需要携带当前行数据，可在这里给offlineForm赋值
      // 例如：this.offlineForm.projectId = row.id; 
      this.offlineDialogVisible = true;
    },

    // 场外上架结束
    // 交易凭证文件选择处理
    handleTradeChange(file, fileList) {
      this.tradeFileList = fileList.slice(-1); // 只保留最后一个选择的文件
      this.uploadForm.tradeProofName = file.name; // 显示文件名
    },

    // 交易凭证文件移除处理
    removeTradeFileList(file, fileList) {
      this.tradeFileList = [];
      this.uploadForm.tradeProofName = ""; // 清空文件名显示
      this.tradeFileUrl = ""; // 清空飞书地址
    },


    // 交易凭证上传成功回调（获取飞书地址）
    upLoadParamTradeFile(response, file, fileList) {
      if (response) {
        this.tradeFileUrl = response.msg; // 保存飞书返回的文件地址
        console.log("交易凭证飞书地址：", this.tradeFileUrl);
      }
    },

    // 交易凭证预览
    tradeFilehandlePreview(file) {
      let tradeFileUrl = file.response.msg;
      openUrlInNewWindow(tradeFileUrl); // 在新窗口打开飞书文件
    },
    handleView(id) {
       this.$router.push({
    path: '/assets/credit/assetDetail',
    query: { id: id } // 通过query传递参数，与详情页的this.$route.query.id对应
  })
     
    },

    handleSubmit() {
      this.$refs.uploadForm.validate((valid) => {
        // 1. 构建提交数据（包含飞书地址）
        const submitData = {
          // 保留表单其他字段
          // carbonMethodology: this.uploadForm.methodology,
          id: this.uploadForm.id,
          carbonProjectName: this.uploadForm.projectName,
          total: this.uploadForm.total,
          buyUnitPrice: this.uploadForm.buyUnitPrice,
          buyTotalPrice: this.uploadForm.buyTotalPrice,
          certifiedAgency: this.uploadForm.certifiedAgency,
          issueDate: this.uploadForm.issueDate,
          buyDate: this.uploadForm.buyDate,
          issuingCertificates:this.uploadForm.issuingCertificates,
          issuingCertificatesFileName: this.uploadForm.holdProofName,
          buyCertificateFileName: this.uploadForm.tradeProofName,
          issuingCertificates: this.tranFileUrl,  // 持仓凭证飞书地址
          buyCertificate: this.tradeFileUrl,  // 交易凭证飞书地址
          carbonProjectId: this.uploadForm.carbonProjectId,
          carbonMethodology: this.uploadForm.methodologyCode,
          carbonExchange:this.uploadForm.carbonExchange
        };
      
        if (valid) {
          const modifyPriceParam = this.modifyPrice ? `&modifyPrice=${this.modifyPrice}` : '';

            this.$request({
              url: `${this.uploadForm.id ? '/assets/carbonCreditAssets/update' : '/assets/carbonCreditAssets/upload'}?rid=${this.rid}${modifyPriceParam}`,
              method: this.uploadForm.id ? 'PUT' : 'POST',
              data: submitData
            }).then(res => {
            if (res.code === 200) {  // 表示成功保存
              this.$message.success(res.msg)
              this.queryCredits()
              this.queryCreditSum();
              this.fromVisible = false
            } else {
              this.$message.error(res.msg)  // 弹出错误的信息
            }
          })
        }
      });
    },

    tranFilehandlePreview(file) {
      let tranFileUrl = file.response.msg;
      openUrlInNewWindow(tranFileUrl);
    },
    handleTranChange(file, fileList) {
      
      this.tranFileList = fileList.slice(-1);
      this.uploadForm.holdProofName = file.name;
    },
    removeFileList(file, fileList) {
      this.tranFileList = [];
      this.tranFileUrl = "";
    },
    upLoadParamTranFile(response, file, fileList) {
      if (response) {
        this.tranFileUrl = response.msg;
        this.uploadForm.issuingCertificates = res.msg
        console.log(this.tranFileUrl);
      }
    },
    // 处理持仓凭证移除（如果组件支持移除操作）
    handleHoldProofRemove() {
      this.uploadForm.holdProof = null;
      this.uploadForm.holdProofName = "";
      // 主动触发表单验证，显示错误提示
      this.$refs.uploadForm.validateField("holdProof");
    },
    // 项目选择弹窗分页大小变更
    handleProjectPageSizeChange(newSize) {
      this.projectPageSize = newSize;
      this.projectPageNum = 1; // 切换条数时重置为第1页
      this.fetchProjectList();
    },

    // 选择项目
    selectProject(row) {
      this.uploadForm.total = row.remainingReduction
      this.uploadForm.projectId = row.id,
      this.rid = row.id
        this.uploadForm.projectName = row.projectName;
      this.uploadForm.carbonMethodologyName = row.methodologyName || ""; // 采用方法学
      this.uploadForm.projectScopeType = row.projectScopeType || ""; // 类型
      this.uploadForm.issuingDate = row.issuingDate
        ? new Date(row.issuingDate)
        : null; // 签发日期
      this.uploadForm.certifiedAgency = row.projectVerifier || ""; // 核证机构
      this.uploadForm.methodologyCode = row.methodologyCode || "";

      this.projectSelectorVisible = false;
    },

    // 打开项目选择弹窗
    openProjectSelector() {
      this.projectSelectorVisible = true;
      this.projectPageNum = 1; // 重置页码
      this.fetchProjectList(); // 加载数据
    },

    // 获取项目列表
    async fetchProjectList() {
      this.projectLoading = true;
      const params = {
        page: this.projectPageNum, // 使用独立页码变量
        pageSize: this.projectPageSize,
        projectName: this.projectSearchKey,
        tenantId: this.user.tenantId,
      };
      try {
        const res = await this.$request.get("/assets/carbonCreditAssets/list", {
          params,
        });
        if (res.code === 200) {
          this.projectTotal = Number(res.data.total) || 0;
          // 同步当前页码（同样转换为数字）
          this.projectPageNum = Number(res.data.current) || 1;
          this.projectList = res.data.records || [];
        }
      } catch (error) {
        this.$message.error("获取项目列表失败，请稍后重试");
        console.error(error);
      } finally {
        this.projectLoading = false;
      }
    },

    // 查询资产统计
    queryCreditSum() {
      this.$request
        .get("/assets/carbonCreditAssets/queryCreditAssetsSum", {
          params: {
            tenantId: this.user.tenantId,
          },
        })
        .then((res) => {
          if (res.code === 200) {
            this.holdTotal = res.data.total || 0;
            this.locked = res.data.lockedAmount || 0;
            this.frozen = res.data.frozenAmount || 0;
            this.available = res.data.availableAmount || 0;
          }
        });
    },

    // 表格选择事件
    handleSelectionChange(selection) {
      console.log("选中的行：", selection);
    },

    // 场外上架操作
    handleOffline(row) {
      this.rid = row.id;
      this.offlineForm.projectId = row.carbonProjectId;
      this.offlineForm.projectScopeCode = row.projectScopeCode;
      this.offlineForm.projectScope = row.projectScope;
      this.offlineDialogVisible = true;
      this.offlineForm.projectType = row.projectScopeTypeCode;
      this.offlineForm.projectName = row.projectName;
      this.offlineForm.publisherId = this.user.tenantId;
      this.offlineForm.contactsName = this.user.accountName;
      this.offlineForm.contactsPhone = this.user.phone;
      this.offlineForm.institutionName = this.user.tenantName;
    },

    // 场内交易操作
    handleInner(row) {
      console.log("场内交易操作，行数据：", row);
    },

    // 按项目搜索
    handleProjectSearch() {
      // 重置为第一页
      this.mainPageNum = 1;
      const params = {
        ...this.form,
        tenantId: this.user.tenantId,
      }
      if (params.certificationCriteria === '0070000000') {
        params.certificationCriteria = null;
      } if (params.transactionStatus === '0160000000') {
        params.transactionStatus = null;
      } if (params.assetsStatus === '0130000000') {
        params.assetsStatus = null;
      }
      this.$request.get('/assets/carbonCreditAssets/queryBySelector', {
        params: params
      }).then(res => {
        if (res.code === 200) {
          this.tableData = res.data.records || [];
          this.mainTotal = res.data.total || 0;
        }
      })
    },

    // 方法学搜索
    handleMethodSearch() {
      // 重置为第一页
      this.mainPageNum = 1;
      const params = {
        ...this.form,
        tenantId: this.user.tenantId,
      }
      if (params.certificationCriteria === '0070000000') {
        params.certificationCriteria = null;
      } if (params.transactionStatus === '0160000000') {
        params.transactionStatus = null;
      } if (params.assetsStatus === '0130000000') {
        params.assetsStatus = null;
      }
      this.$request.get('/assets/carbonCreditAssets/queryBySelector', {
        params: params
      }).then(res => {
        if (res.code === 200) {
          this.tableData = res.data.records || [];
          this.mainTotal = res.data.total || 0;
        }
      })
    },

    // 主表格分页切换
    handleMainPageChange(val) {
      this.mainPageNum = val;
      this.queryCredits();
    },

    // 主表格分页大小变更
    handleMainPageSizeChange(val) {
      this.mainPageSize = val;
      this.mainPageNum = 1;
      this.queryCredits();
    },

    // 筛选条件变更时重置主表格分页
    resetMainPagination() {
      this.mainPageNum = 1;
      this.queryCredits();
    },

    // 选择项目
    handleProjectSelect(selection) {
      this.selectedProjects = selection;
    },

    // 关闭项目选择弹窗
    handleProjectSelectorClose() {
      this.selectedProjects = [];
      this.projectSearchKey = "";
    },

    // 项目选择弹窗分页切换
    handleProjectPageChange(newPage) {
      this.projectPageNum = newPage;
      this.fetchProjectList();
    },

    // 文件上传相关方法
    handleHoldProofChange(file) {
      this.uploadForm.holdProof = file.raw;
      this.uploadForm.holdProofName = file.name;
    },

    handleTradeProofChange(file) {
      this.uploadForm.tradeProof = file.raw;
      this.uploadForm.tradeProofName = file.name;
    },
  },
};
</script>

<style lang="scss" scoped>
.carbon-credit-page {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 64px);
  font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}

::v-deep .project-selector-table {
  border: none !important;
}

::v-deep .project-selector-table .el-table__header,
::v-deep .project-selector-table .el-table__body,
::v-deep .project-selector-table .el-table__row,
::v-deep .project-selector-table th,
::v-deep .project-selector-table td {
  border: none !important;
  border-collapse: collapse !important;
}

/* 顶部栏样式 */
.top-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #e6f7ed;
  padding: 10px 20px;
  border-radius: 4px;
  margin-bottom: 20px;

  .header-left {
    display: flex;
    align-items: center;

    .title {
      font-size: 16px;
      font-weight: bold;
      color: #52c41a;
      margin-left: 8px;
    }
  }

  .header-middle {
    color: #666;
    text-align: left;
    flex: 1;
    margin: 0 20px;
    font-size: 14px;

    .stat-item {
      margin-right: 10px;
    }

    .stat-value {
      color: #6cba12;
      font-weight: 700;
    }
  }

  .header-right {
    button {
      margin-left: 10px;
      &.el-button--primary {
        border-color: #409eff;
        color: #409eff;
      }
      &.el-button--success {
        border-color: #67c23a;
        color: #67c23a;
      }
    }
  }
}

/* 筛选区域样式 */
.filter-section {
  background: #f8f9fa;
  padding: 20px;
  margin-bottom: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;

  .filter-row,
  .search-row {
    display: flex;
    flex-wrap: wrap;
  }

  .filter-item {
    margin-bottom: 10px;
  }

  .filter-label {
    display: inline-block;
    font-size: 14px;
    color: #666;
    margin-bottom: 4px;

    min-width: 60px;
  }

  .filter-label2 {
    display: inline-block;
    font-size: 14px;
    color: #666;
    margin-bottom: 4px;
    width: 100px;

  }

  .filter-select,
  .filter-date {
    width: 100%;
    --el-input-border-color: #dcdfe6;
  }

  .search-container {
    display: flex;
    align-items: center;
    width: 100%;
  }

  .search-input {
    flex: 1;
    margin-right: 10px;
    --el-input-border-color: #dcdfe6;
  }
}

/* 操作按钮样式 */
.operation-btns {
  display: flex;
  gap: 10px;
  align-items: center;
  justify-content: center;

  .btn-text {
    cursor: pointer;
    color: #409eff;
    &.view {
      color: #409eff;
    }
    &.offline {
      color: #409eff;
    }
    &.inner {
      color: #67c23a;
    }
    &.modify {
      color: #f5a623;
    }
    &.delete {
      color: #f56c6c;
    }
    &:hover {
      text-decoration: underline;
    }
  }
}

/* 分页样式 */
.pagination {
  margin-top: 15px;
  text-align: right;
  padding: 10px 0;
}

/* 上传弹窗样式 */
.upload-dialog-content {
  padding: 20px 40px;
}

.form-row {
  margin-bottom: 5px;
}

.file-name {
  margin-top: 6px;
  color: #666;
  font-size: 12px;
  max-width: 300px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

::v-deep .el-form-item__label {
  font-weight: 1000;
}

::v-deep .el-upload__tip {
  margin-top: 5px !important;
}

/* 项目选择弹窗样式 */
.project-search-bar {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.project-pagination {
  text-align: right;
  margin-top: 15px;
}
</style>
